//
//  DaishouDetailViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/10/23.
//  Copyright © 2015年 xingrong. All rights reserved.
//

#import "DaishouDetailViewController.h"
#import "ExpressDetailViewController.h"
#import "DaishouScanViewController.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "Daishou.h"
#import "DaishouExpress.h"
#import "DaishouDetailCell.h"
#import "UIImageView+WebCache.h"
#import "DaishouAlertView.h"
#import "RefuseAlertView.h"
#import "CustomButton.h"
#import "NoviceView.h"

@interface DaishouDetailViewController ()<SocketRequestDelegate,DaishouAlertViewDelegate,RefuseAlertViewDelegate,ExpressDetailViewControllerDelegate> {
    SocketRequest *_socketRequest;
    NSMutableArray *_expressList;
    NSIndexPath *_currentIndexPath;
    
    int _type;
}

@end

@implementation DaishouDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        _expressList = [NSMutableArray arrayWithCapacity:1];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.daishou.handleType == 2) {
        [self.tableView reloadData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self handelNetWorkMethod];

    _logoImageView.layer.cornerRadius = 4;
    _logoImageView.clipsToBounds = YES;
    NSString *companyUrl = [self.daishou.companyLogo stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
    NSURL *logoUrl = [NSURL URLWithString:companyUrl];
    [_logoImageView sd_setImageWithURL:logoUrl placeholderImage:[UIImage imageNamed:@"yijskd_logo_bg"]];
    _expressCompanyLabel.text = self.daishou.companyName;
    _timeLabel.text = [NSString stringWithFormat:@"%@ %@",self.daishou.showDay,self.daishou.showTime];
    _nameLabel.attributedText = [self nameAttributedText];
    [self getDaishouDetailListSocket];
    if (self.daishou.handleType != 1) {
        _footerView.hidden = YES;
    } else {
        self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    }
    _scanBtn.hidden = YES;
    if (self.daishou.handleType == 2) {
        _scanBtn.hidden = NO;
        //判断是否第一次显示已处理待收页面
        BOOL isShowDaishou = [[[NSUserDefaults standardUserDefaults] objectForKey:FirstGuideDaishou] boolValue];
        if (!isShowDaishou) {
            [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:FirstGuideDaishou];
            [[NSUserDefaults standardUserDefaults] synchronize];
            NoviceView *noviceView = [[NoviceView alloc] initWithType:NoviceTypeDaishou];
            [noviceView show];
        }
    }
    [self reloadTableView];
}

- (NSAttributedString *)nameAttributedText {
    NSString *string = [NSString stringWithFormat:@"%@ %@",self.daishou.expresserName,self.daishou.expresserTelephone];
    NSRange range = [string rangeOfString:self.daishou.expresserTelephone];
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string];
    [attString addAttribute:NSForegroundColorAttributeName value:OrangeColor range:range];
    return attString;
}

- (void)successBackLastViewController {
    if (_type == 0) {
        if ([_delegate respondsToSelector:@selector(daishouDetailVCIsRefuse:)]) {
            [_delegate daishouDetailVCIsRefuse:YES];
        }
    } else if (_type == 1) {
        if ([_delegate respondsToSelector:@selector(daishouDetailVCIsRefuse:)]) {
            [_delegate daishouDetailVCIsRefuse:NO];
        }
    }
    [self backLastViewController];
}

- (void)getDaishouDetailListSocket {
    [self.tableView makeLoading];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STRC"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:self.daishou.batchNo] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

//处理本批次快件 0表示拒收 1表示接收
- (void)handleBatchExpressesReason:(NSString *)reason {
    [ToastActivity makeActivity:@"加载中..." InView:self.view];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STSE"]];
    NSString *typeString = [NSString stringWithFormat:@"%d",_type];
    [mutableData appendBytes:[SocketMethod checkLegal:typeString] length:1];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:self.daishou.batchNo] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:self.daishou.expressType] length:1];
    [mutableData appendBytes:[SocketMethod checkLegal:self.daishou.expresserId] length:64];
    if (_type == 0) {
        NSData *reasonData = [reason dataUsingEncoding:NSUTF8StringEncoding];
        NSData *reasonLengthData = [SocketMethod hexDataWithLength:reasonData.length];
        [mutableData appendData:reasonLengthData];
        [mutableData appendData:reasonData];
    } else {
        NSData *lengthData = [SocketMethod hexDataWithLength:0];
        [mutableData appendData:lengthData];
    }
    [_socketRequest addSocketData:mutableData SocketTag:2];
}

- (void)reloadTableView {
    if (self.daishou.handleType == 1) {
        self.title = [NSString stringWithFormat:@"待接收快件(%d)",_expressList.count];
    } else if (self.daishou.handleType == 2) {
        self.title = [NSString stringWithFormat:@"已接收快件(%d)",_expressList.count];
    } else if (self.daishou.handleType == 3) {
        self.title = [NSString stringWithFormat:@"已拒收快件(%d)",_expressList.count];
    }
    [self.tableView reloadData];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    if (socket.socketTag == 1) {
        [self.tableView makeNone];
        if ([code isEqualToString:SuccessSocket]) {
            NSString *content = [SocketMethod stringDecryHexData:data];
            DLog(@"%@",content);
            NSArray *array = [content componentsSeparatedByString:@"|"];
            for (NSString *string in array) {
                if (string.length > 0) {
                    DaishouExpress *express = [[DaishouExpress alloc] initWithString:string];
                    [_expressList addObject:express];
                }
            }
            self.title = [NSString stringWithFormat:@"待处理快件(%d)",_expressList.count];
            NSString *btnTitle = [NSString stringWithFormat:@"同意收件(%d)",_expressList.count];
            [_agreeBtn setTitle:btnTitle forState:UIControlStateNormal];
            [self reloadTableView];
        } else {
            [self.tableView makeTip:msg];
        }
    } else if (socket.socketTag == 2) {
        if ([code isEqualToString:SuccessSocket]) {
            if (_type == 0) {
                [ToastActivity makeSuccess:@"已拒收该批次快件" InView:self.view];
            } else if (_type == 1) {
                [ToastActivity makeSuccess:@"收件成功" InView:self.view];
            }
            [self performSelector:@selector(successBackLastViewController) withObject:nil afterDelay:0.5];
        } else {
            [ToastActivity makeError:msg InView:self.view];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    if (socket.socketTag == 1) {
        [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getDaishouDetailListSocket)];
    } else if (socket.socketTag == 2) {
        [ToastActivity dismissInView:self.view];
    }
    [DSToast showText:msg InView:self.view];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _expressList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"DaishouDetailCell";
    DaishouDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"DaishouDetailCell" owner:self options:nil] lastObject];
        if (self.daishou.handleType != 3) {
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
        } else {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
    DaishouExpress *express = [_expressList objectAtIndex:indexPath.row];
    if (self.daishou.handleType == 1) {
        [cell reloadDaishouDetailCell:express isShowAddress:YES];
    } else {
        [cell reloadDaishouDetailCell:express isShowAddress:NO];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.daishou.handleType == 1) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        _currentIndexPath = indexPath;
        DaishouExpress *express = [_expressList objectAtIndex:indexPath.row];
        DaishouAlertView *alert = [[DaishouAlertView alloc] initWithDaishouExpress:express];
        alert.delegate = self;
        [alert show];
    } else if (self.daishou.handleType == 2) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        DaishouExpress *express = [_expressList objectAtIndex:indexPath.row];
        ExpressDetailViewController *expressDVC = [[ExpressDetailViewController alloc] initWithNibName:@"ExpressDetailViewController" bundle:nil];
        expressDVC.inwayExpressId = express.inWayExpressId;
        expressDVC.delegate = self;
        expressDVC.indexPath = indexPath;
        [self.navigationController pushViewController:expressDVC animated:YES];
    }
}

#pragma mark ExpressDetailViewControllerDelegate
- (void)updateExpress:(NSIndexPath *)indexPath Telephone:(NSString *)telephone Address:(NSString *)address {
    DaishouExpress *express = [_expressList objectAtIndex:indexPath.row];
    express.telephone = telephone;
    express.address = address;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark DaishouAlertViewDelegate
- (void)changeDaishouExpressSuccess {
    [self.tableView reloadRowsAtIndexPaths:@[_currentIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark NibAction
- (IBAction)startScanningButton:(id)sender {
    DaishouScanViewController *daishouSVC = [[DaishouScanViewController alloc] initWithNibName:@"DaishouScanViewController" bundle:nil];
    daishouSVC.expressList = _expressList;
    [self.navigationController pushViewController:daishouSVC animated:YES];
}

- (IBAction)buttonAction:(UIButton *)sender {
    if (sender.tag == 10) {//拒绝
        _type = 0;
        RefuseAlertView *alert = [[RefuseAlertView alloc] initWithResuseAlertViewDelegate:self];
        [alert show];
    } else if (sender.tag == 11) {//同意
        _type = 1;
        [self handleBatchExpressesReason:nil];
    }
}

#pragma mark RefuseAlertViewDelegate
- (void)refuseReceiveExpressReason:(NSString *)reason {
    [self handleBatchExpressesReason:reason];
}

@end
